import { _decorator, Component, Node,  Collider2D,Contact2DType,director,Director } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('PlayerManager')
export class PandaManager extends Component {
    // 接到的红包数量
    pickUpNumber: number = 0
    // 熊猫横坐标
    x: number = 0
    update(deltaTime: number) {
        // 虚拟坐标转成场景坐标
        this.node.setPosition(this.x,this.node.getPosition().y)
    }
    init() {
        // 触摸监听
        this.node.on(Node.EventType.TOUCH_MOVE, (event:any) => {
            this.move(event.touch.getUILocationX() - 375)
        }, this);
        // 开启碰撞监听
        let collider = this.node.getComponent(Collider2D);
        if (collider) {
            collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
    }
    // 碰撞监听回调
    onBeginContact (selfCollider: Collider2D,otherCollider: Collider2D) {
        director.once(Director.EVENT_AFTER_PHYSICS, ()=>{
            this.pickUpNumber++
            otherCollider.node.destroy();
            console.log(this.pickUpNumber,'接到的红包数量')
        })

    }
    move(targetX:number) {
        // 控制离屏幕边缘间距
        const gap = 105
        const maxX = 375
        const minX = -375
        if (targetX > maxX - gap) {
            targetX = maxX - gap
        } else if (targetX < minX + gap) {
            targetX = minX + gap
        }
        this.x = targetX
    }
}


